package com.seven.netty.protocol.handler;

import com.seven.netty.protocol.bean.Body;
import com.seven.netty.protocol.bean.Head;
import com.seven.netty.protocol.bean.Message;
import com.seven.netty.protocol.constants.NettyConstant;
import com.seven.netty.protocol.enums.MessageTypeEnum;
import com.seven.netty.protocol.utils.ByteUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * @author chendongdong
 * @description TODO
 * @since 2024/3/6 11:51
 */
@Slf4j
public class LoginReqHandler extends ChannelInboundHandlerAdapter {
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Head head = Head.builder()
            .headIndex(NettyConstant.HEAD_INDEX)
            .version(NettyConstant.VERSION)
            .sessionId(23l)
            .crcCode(1)
            .messageType(MessageTypeEnum.HANDSHAKE_REQUEST.getType().byteValue())
            .build();

        Map<String, Object> attachment = new HashMap<>();
        attachment.put("dev", "2534");
        attachment.put("name", "张三");
        head.setAttachments(attachment);
        Body body = new Body();
        body.setPayload("welcom to zhangsan");
        Message message = Message.builder().head(head).body(body).build();
        int len = ByteUtil.calculateLength(message);
        message.getHead().setLength(len);
        ctx.writeAndFlush(message);
    }

    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Message message = (Message) msg;
        if (message != null && message.getHead().getMessageType() == MessageTypeEnum.HANDSHAKE_RESPONSE.getType().byteValue()) {
            log.debug("握手响应:{}", message);
        } else {
            ctx.fireChannelRead(msg);
        }
    }

    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.fireChannelReadComplete();
    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.fireExceptionCaught(cause);
    }
}
